﻿#define _CRT_SECURE_NO_WARNINGS 1

//在排序数组中查找元素的第⼀个和最后⼀个位置（medium）:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/submissions/566225986/
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.empty())
        {
            return { -1,-1 };
        }
        int begin = 0, end = 0;
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] <= target)
            {
                left = mid;
            }
            else
            {
                right = mid - 1;
            }
        }
        if (nums[left] == target)     end = left;
        else      return { -1,-1 };

        left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target)
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }
        begin = left;

        return { begin,end };
    }
};

//搜索插⼊位置（easy）:https://leetcode.cn/problems/search-insert-position/
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target)
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }

        // return left;
        if (left == n - 1 && nums[left] < target)
        {
            return n;
        }
        else
        {
            return left;
        }
    }
};
